package me.algo.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @author guozheng
 * @date 2024/4/13
 */
public class T1 {

    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<TreeNode> stk = new LinkedList<>();
        LinkedList<TreeNode> rtn = new LinkedList<>();
        if (root == null) {
            return new ArrayList<>();
        }
        stk.addLast(root);
        while (!stk.isEmpty()) {
            TreeNode pop = stk.removeLast();
            rtn.addLast(pop);
            if (pop.left != null) {
                stk.addLast(pop.left);
            }
            if (pop.right != null) {
                stk.addLast(pop.right);
            }
        }
        List<Integer> result = new ArrayList<>();
        while (!rtn.isEmpty()) {
            TreeNode node = rtn.removeLast();
            result.add(node.val);
        }
        return result;
    }

    /**
     * 前序遍历
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> rtn = new ArrayList<>();
        LinkedList<TreeNode> stk = new LinkedList<>();
        TreeNode cur = root;
        while (cur != null || !stk.isEmpty()) {
            if (cur != null) {
                int val = cur.val;
                rtn.addLast(val);
                stk.add(cur);
                cur = cur.left;
            } else {
                TreeNode node = stk.removeLast();
                cur = node.right;
            }
        }
        return rtn;
    }


    /**
     * 中序遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> rtn = new ArrayList<>();
        if (Objects.isNull(root)) {
            return rtn;
        }
        LinkedList<TreeNode> stk = new LinkedList<>();
        TreeNode cur = root;
        while (cur != null || !stk.isEmpty()) {
            if (cur != null) {
                stk.addLast(cur);
                cur = cur.left;
            } else {
                cur = stk.removeLast();
                int val = cur.val;
                rtn.add(val);
                cur = cur.right;
            }
        }
        return rtn;
    }
}
